﻿
using System;
using Microsoft.VisualStudio.SharePoint.Explorer;
using System.ComponentModel.Composition;
using Microsoft.VisualStudio.SharePoint.Explorer.Extensions;
using Microsoft.VisualStudio.SharePoint;
using CodeCounsel.SharePoint.DevTools.Commands;
using Scope = CodeCounsel.SharePoint.DevTools.Commands.FeatureScope;
using System.Windows.Forms;
using Microsoft.Win32;
using System.IO;
using System.Diagnostics;

namespace CodeCounsel.SharePoint.DevTools.ExplorerNodeExtensions
{
    [Export(typeof(IExplorerNodeTypeExtension))]
    [ExplorerNodeType(ExplorerNodeTypes.SiteNode)]
    public class SiteNodeExtension
        : IExplorerNodeTypeExtension
    {
        public void Initialize(IExplorerNodeType nodeType)
        {
            nodeType.NodeChildrenRequested += NodeChildrenRequested;
            nodeType.NodeMenuItemsRequested += NodeMenuItemsRequested;
        }

        void NodeMenuItemsRequested(object sender, ExplorerNodeMenuItemsRequestedEventArgs e)
        {
            IMenuItem item = e.MenuItems.Add("Open In SharePoint Designer");
            item.Click += delegate
            {
                IExplorerSiteNodeInfo nodeInfo = e.Node.GetAnnotation<IExplorerSiteNodeInfo>();
                string url = nodeInfo.Url.ToString();
                OpenInSharePointDesigner(url);
            };
        }

        void NodeChildrenRequested(object sender, ExplorerNodeEventArgs e)
        {
            GenericFolderNode.Create(e.Node, "Fields", new Action<IExplorerNode>(FieldNodeTypeProvider.CreateFieldNodes));
            GenericFolderNode.Create(e.Node, "Web Parts", new Action<IExplorerNode>(WebPartNodeTypeProvider.CreateWebPartNodes));
            GenericFolderNode.Create(e.Node, "Master Pages", new Action<IExplorerNode>(MasterPageNodeTypeProvider.CreateMasterPageNodes));
            GenericFolderNode.Create(e.Node, "Themes", new Action<IExplorerNode>(ThemeNodeTypeProvider.CreateThemeNodes));
        }

        void OpenInSharePointDesigner(string url)
        {
            RegistryKey key = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Office\14.0\SharePoint Designer\InstallRoot");
            //if (key != null)
            {
                string path = Path.Combine(
                    @"C:\Program Files\Microsoft Office\Office14",
                    //    Convert.ToString(key.GetValue("Path"));
                    "SPDesign.exe");

                if (File.Exists(path))
                {
                    ProcessStartInfo startInfo = new ProcessStartInfo(
                        path, url);
                    Process.Start(startInfo);
                }
            }
        }
    }
}
